#include "str_hex.h"
#include <ctype.h>

void hexstr_to_byte(const char *source, unsigned int sourceLen, unsigned char *dest) {
    unsigned char highByte, lowByte;

    for (int i = 0; i < sourceLen; i += 2) {
        highByte = toupper(source[i]);
        lowByte = toupper(source[i + 1]);

        if (highByte > 0x39)
            highByte -= 0x37;
        else
            highByte -= 0x30;

        if (lowByte > 0x39)
            lowByte -= 0x37;
        else
            lowByte -= 0x30;

        dest[i / 2] = (highByte << 4) | lowByte;
    }
}

void byte_to_hexstr(const unsigned char *source, unsigned int sourceLen, char *dest) {
    unsigned char highByte, lowByte;

    for (int i = 0; i < sourceLen; i++) {
        highByte = 48 + source[i] / 16;
        lowByte = 48 + source[i] % 16;
        if (highByte > 57) {
            highByte = highByte + 7;
        }

        if (lowByte > 57) {
            lowByte = lowByte + 7;
        }

        dest[i * 2] = highByte;
        dest[i * 2 + 1] = lowByte;
    }

    dest[sourceLen * 2] = '\0';
}

void uint_to_byte(unsigned int source, unsigned char *dest) {
    dest[0] = ((source & 0xFF000000) >> 24);
    dest[1] = ((source & 0xFF0000) >> 16);
    dest[2] = ((source & 0xFF00) >> 8);
    dest[3] = (source & 0xFF);
}

void byte_to_uint(const unsigned char *source, unsigned int *dest) {
    *dest += ((source[0] << 24) & 0xFF000000);
    *dest += ((source[1] << 16) & 0xFF0000);
    *dest += ((source[2] << 8) & 0xFF00);
    *dest += (source[3] & 0xFF);
}

void ushort_to_byte(unsigned short source, unsigned char *dest) {
    dest[0] = ((source & 0xFF00) >> 8);
    dest[1] = (source & 0xFF);
}

void byte_to_ushort(const unsigned char *source, unsigned short *dest) {
    *dest += ((source[0] << 8) & 0xFF00);
    *dest += (source[1] & 0xFF);
}
